package com.dream.sys.service.impl;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dream.commons.result.PageInfo;
import com.dream.commons.utils.BeanUtils;
import com.dream.commons.utils.StringUtils;
import com.dream.sys.mapper.UserMapper;
import com.dream.sys.mapper.UserRoleMapper;
import com.dream.sys.model.User;
import com.dream.sys.model.UserRole;
import com.dream.sys.model.DTO.roleDto.RoleDto;
import com.dream.sys.model.DTO.userDto.ChangePwdReqDto;
import com.dream.sys.model.DTO.userDto.UserDto;
import com.dream.sys.model.DTO.userDto.UserListReqDto;
import com.dream.sys.scan.MyException;
import com.dream.sys.service.UserService;
import com.dream.sys.shiro.PasswordHash;
import com.dream.sys.shiro.ShiroUser;




/**
 *
 * User 表数据服务层接口实现类
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private PasswordHash passwordHash;
    
    /**
     * 根据id查找用户
     */
    @Override
    public List<User> selectByLoginName(UserDto userDto) {
        User user = new User();
        user.setLoginName(userDto.getLoginName());
        EntityWrapper<User> wrapper = new EntityWrapper<User>(user);
        if (null != userDto.getId()) {
            wrapper.where("id != {0}", userDto.getId());
        }
        return this.selectList(wrapper);
    }

    /**
     * 新增用户
     */
    @Override
    public void insertByDto(UserDto userDto) {
        User user = BeanUtils.copy(userDto, User.class);
        user.setCreateTime(new Date());
        this.insert(user);
        
        Long id = user.getId();
        String[] roles = userDto.getRoleIds().split(",");
        for (String roleId : roles) {
            UserRole userRole = new UserRole();
            userRole.setUserId(id);
            userRole.setRoleId(Long.valueOf(roleId));
            userRoleMapper.insert(userRole);
        }
    }
   
    /**
     * 跟新用户具体信息
     */
    @Override
    public void updateByDto(UserDto userDto) {
        User user = BeanUtils.copy(userDto, User.class);
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        }
        this.updateById(user);
        
        Long id = userDto.getId();
        List<UserRole> userRoles = userRoleMapper.selectByUserId(id);
        if (userRoles != null && !userRoles.isEmpty()) {
            for (UserRole userRole : userRoles) {
                userRoleMapper.deleteById(userRole.getId());
            }
        }

        String[] roles = userDto.getRoleIds().split(",");
        UserRole userRole = new UserRole();
        for (String string : roles) {
            userRole.setUserId(id);
            userRole.setRoleId(Long.valueOf(string));
            userRoleMapper.insert(userRole);
        }
    }

    /**
     * 用户列表
     */
    @Override
    public PageInfo<User> selectDataGrid(UserListReqDto userListReqDto){
    	Page<User> page = new Page<User>();
		page.setCurrent(userListReqDto.getPage());
		page.setSize(userListReqDto.getLimit());
		String loginName = userListReqDto.getLoginName();
		EntityWrapper<User> ew = new EntityWrapper<User>();
		if (StringUtils.isNotBlank(loginName)) {
			ew.like("login_name", loginName);
		}
		ew.orderBy("create_time", false);
		Page<User> pageInfo = this.selectPage(page, ew);
		PageInfo<User> into = new PageInfo<User>(pageInfo.getTotal(), pageInfo.getRecords());
		return into;
    }
    
    /**
     * 根据id删除用户
     */
    @Override
    public void deleteUserById(Long id) {
        this.deleteById(id);
        userRoleMapper.deleteByUserId(id);
    }
    
    /**
     * 批量删除user
     * @param ids
     * @return
     */
    @Override
	public int deleteUsers(String[] ids) {
		List<String> idsList = Arrays.asList(ids);
		for (String id : idsList) {
			userRoleMapper.deleteByUserId(Long.parseLong(id));
		}
		int s = userMapper.deleteBatchIds(idsList);
		if (s <= 0) {
			String msg ="操作失败";
			throw new MyException(msg);
		}
		return s;
	}

    /**
   	 * 修改密码
   	 * @param changePwdReqDto
   	 * @return
   	 */
    @Transactional
	@Override
	public String changePwd(ChangePwdReqDto changePwdReqDto) {
		String msg="";
		ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		User user = userMapper.selectById(shiroUser.getId());
		String salt = user.getSalt();
	    if (!user.getPassword().equals(passwordHash.toHex(changePwdReqDto.getYpassword(), salt))) {
	    	msg = "原始密码不正确";
	    	throw new MyException(msg);
	    }
	    if (!changePwdReqDto.getZpassword().equals(changePwdReqDto.getQpassword())){
	    	msg = "新密码不一致";
	    	throw new MyException(msg);
	    }
	    this.updatePwdByUserId(user.getId(), passwordHash.toHex(changePwdReqDto.getZpassword(), salt));
	        msg="修改成功";
		return msg;
	}
    
    /**
     * 修改密码
     * @param userId
     * @param md5Hex
     */
    public void updatePwdByUserId(Long userId, String md5Hex) {
        User user = new User();
        user.setId(userId);
        user.setPassword(md5Hex);
        this.updateById(user);
    }

    
    /**
     * 个人用户详情
     */
    @Override
    public UserDto selectDtoById(Long id) {
    	UserDto userDto = userMapper.selectUserDtoById(id);
    	List<RoleDto> rolesList = userDto.getRolesList();
    	//拼接角色名称
    	String roleNames="";
    	for (RoleDto roleDto : rolesList) {
    		roleNames = roleNames + roleDto.getName() + ",";
		}
    	roleNames = roleNames.substring(0,roleNames.length()-1);
    	userDto.setRoleNames(roleNames);
        return userDto;
    }

}